package org.taskexecution.taskexecution.application.socialsecurity;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cephr.accountcenter.application.socialsecurity.PersonalGjjInfoService;
import com.cephr.accountcenter.application.socialsecurity.PersonalSocialInfoService;
import com.cephr.accountcenter.application.staff.StaffService;
import com.cephr.accountcenter.infrastructure.common.constant.Constants;
import com.cephr.accountcenter.infrastructure.presistent.mapper.socialsecurity.PersonalSocialInfoMapper;
import com.cephr.accountcenter.infrastructure.presistent.po.miniapp.StaffMiniPO;
import com.cephr.accountcenter.infrastructure.presistent.po.socialsecurity.PersonalSocialInfo;
import com.cephr.accountcenter.infrastructure.presistent.po.socialsecurity.SocialSecurityInsure;
import com.cephr.accountcenter.task.ITaskHandler;
import com.cephr.accountcenter.userinterface.request.socialsecurity.SaveSocialBatch;
import com.cephr.accountcenter.userinterface.request.socialsecurity.SocialInsuranceQueryDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Lydond
 * @description:
 * @create_date: 2025/6/30-下午4:48
 */
@Service
//日志
@Slf4j
@Component
public class PersonalSocialInfoServiceImpl extends ServiceImpl<PersonalSocialInfoMapper, PersonalSocialInfo> implements PersonalSocialInfoService, ITaskHandler {

    // 使用全局配置的 ObjectMapper，避免各处自建导致配置不一致
    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private StaffService staffService;

    @Resource
    private PersonalGjjInfoService personalGjjInfoService;

    @Override
    public SaveSocialBatch saveBatchSocial(SaveSocialBatch saveSocialBatch) {
        SaveSocialBatch saveSocialBatches = new SaveSocialBatch();
        if (CollectionUtils.isEmpty(saveSocialBatch.getData())) {
            return saveSocialBatch;
        }
        List<PersonalSocialInfo> allRecords = new ArrayList<>();
        List<PersonalSocialInfo> unmatchedList = new ArrayList<>();
        for (PersonalSocialInfo info : saveSocialBatch.getData()) {
            StringBuilder errorMsg = new StringBuilder();
            boolean valid = true;

            // 校验身份证
            if (StringUtils.isEmpty(info.getC2()) || !info.getC2().matches("^[1-9]\\d{5}(18|19|20)?\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$")) {
                errorMsg.append("身份证格式错误；");
                valid = false;
            }
            // 校验C4
            if (StringUtils.isEmpty(info.getC4()) || !info.getC4().matches("^\\d{6}$")) {
                errorMsg.append("费用所属期格式错误；");
                valid = false;
            }
            // 校验C5
            if (StringUtils.isEmpty(info.getC5()) || !info.getC5().matches("^\\d{6}$")) {
                errorMsg.append("结算期格式错误；");
                valid = false;
            }

            if (valid) {
                allRecords.add(info);
            } else {
                info.setErrorMsg(errorMsg.toString());
                unmatchedList.add(info);
            }
        }


        List<PersonalSocialInfo> existingRecords = new ArrayList<>();
        List<PersonalSocialInfo> newRecords = new ArrayList<>();
        Map<String, PersonalSocialInfo> atRecords = findAtRecords(allRecords, saveSocialBatch.getPayAccountId());

        // 遍历所有记录，分离出已存在的记录和新记录
        for (PersonalSocialInfo info : allRecords) {
            String key = buildKey(info.getC2(), info.getC4(), info.getC5(), saveSocialBatch.getPayAccountId());
            if (atRecords.containsKey(key)) {
                // 如果记录已存在，更新其信息
                info.setId(atRecords.get(key).getId()); // 设置ID以便更新
                existingRecords.add(info);
            } else {
                // 如果记录不存在，添加到新记录列表
                newRecords.add(info);
            }
        }


        List<String> idCards = allRecords.stream()
                .map(PersonalSocialInfo::getC2)
                .distinct()
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

        List<StaffMiniPO> staffMiniPOS = staffService.queryStaffInfoInIdCards(idCards, Constants.TYPE_ZERO);


        // 将身份证号与员工信息关联
        Map<String, StaffMiniPO> staffMap = staffMiniPOS.stream()
                .collect(Collectors.toMap(StaffMiniPO::getIdCard, staff -> staff, (existing, replacement) -> existing));

        // 设置公共字段
        List<PersonalSocialInfo> notSystemList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(newRecords)) {
            setCommonRecord(saveSocialBatch, newRecords, staffMap, notSystemList, true);
            this.saveBatch(newRecords);
        }

        if (ObjectUtil.isNotEmpty(existingRecords)) {
            //批量更新已存在的记录
            setCommonRecord(saveSocialBatch, existingRecords, staffMap, notSystemList, false);
            this.updateBatchById(existingRecords);
        }

        // 返回保存成功的记录
        saveSocialBatches.setSuccessList(newRecords);
        saveSocialBatches.setUnmatchedList(unmatchedList);
        saveSocialBatches.setNotSystemList(notSystemList);
        saveSocialBatches.setUpdateList(existingRecords);
        saveSocialBatches.setBillMonth(saveSocialBatch.getBillMonth());
        saveSocialBatches.setPayAccountId(saveSocialBatch.getPayAccountId());
        saveSocialBatches.setTicketId(saveSocialBatch.getTicketId());
        if (CollectionUtils.isEmpty(allRecords)) {
            return saveSocialBatches;
        }
        return saveSocialBatches;
    }


    /**
     * 构建唯一键
     */

    private String buildKey(String c2, String c4, String c5, Long payAccountId) {
        return payAccountId != null
                ? String.join("|", c2, c4, c5, String.valueOf(payAccountId))
                : String.join("|", c2, c4, c5);
    }


    @Override
    public Object execute(String params) throws Exception { // 1. 声明 throws Exception
        // 1. 参数校验 (如果校验失败，就应该抛出异常)
        if (StrUtil.isBlank(params)) {
            log.warn("execute: params 为空");
            throw new IllegalArgumentException("参数为空");
        }

        // 2. 参数解析
        SaveSocialBatch taskParams = new SaveSocialBatch();
        try {
            // 让 Jackson 自动处理所有类型转换和嵌套解析
            taskParams = objectMapper.readValue(params, SaveSocialBatch.class);
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            log.error("参数解析失败，params={}", params, e);
            throw new IllegalArgumentException("参数解析失败: " + e.getMessage());
        }

        // 3. 执行核心业务
        log.info("开始处理社保业务, ticketId={}, payAccountId={}", taskParams.getTicketId(), taskParams.getPayAccountId());
        return saveBatchSocial(taskParams);
    }

    @Override
    public String getTaskKey() {
        return "SOCIAL_INFO_UPDATE_TASK";
    }
}
